app.controller("goodsManagementController",function ($scope,$controller,$location,goodsManagementService,goodsCategoryService,uploadFileService,goodsTemplateService) {
    $controller("commonController",{$scope:$scope});

    $scope.searchEntity={};//定义搜索对象
    //搜索
    $scope.search=function(pageNum,pageSize){
        goodsManagementService.search(pageNum,pageSize,$scope.searchEntity).success(
            function(response){
                $scope.list=response.result;
                $scope.paginationConf.totalItems=response.total;//更新总记录数
            }
        );
    }

    //更新商品状态
    $scope.updateAuditStatus=function(status){
        goodsManagementService.updateAuditStatus($scope.selectedIds,status).success(
            function (response) {
                if (200==response.code){
                    alert(response.message);
                    $scope.reloadList();
                }else{
                    alert(response.object);
                    $scope.reloadList();
                }
            }
        )
    }

    //查询实体
    $scope.findOne=function(){
        var id=$location.search()['id'];
        //如果 id 为空，则返回，避免和添加商品时冲突
        if (id == null){
            return;
        }
        goodsManagementService.findOne(id).success(
            function(response){
                $scope.entity= response;
                //获取商品介绍，给到富文本编辑器
                editor.html($scope.entity.dpGoodsDesc.introduction);
                //转换图片路径为 json 对象，数据库中存的是 string 类型
                $scope.entity.dpGoodsDesc.itemImages=JSON.parse($scope.entity.dpGoodsDesc.itemImages);
                //转换扩展属性为 json 对象以供页面显示，因为数据库中存的是 string 类型
                $scope.entity.dpGoodsDesc.customAttributeItems=JSON.parse($scope.entity.dpGoodsDesc.customAttributeItems);
                //转换规格
                $scope.entity.dpGoodsDesc.specificationItems=JSON.parse($scope.entity.dpGoodsDesc.specificationItems);
                //转换 sku 表的 spec 规格选项
                for (var i=0;i<$scope.entity.dpItemList.length;i++){
                    $scope.entity.dpItemList[i].spec=JSON.parse($scope.entity.dpItemList[i].spec);
                }
            }
        );
    }
    //保存
    $scope.save=function(){
        $scope.entity.dpGoodsDesc.introduction=editor.html();
        var serviceObject;//服务层对象
        if($scope.entity.dpGoods.id!=null){//如果有ID
            serviceObject=goodsManagementService.update( $scope.entity ); //修改
        }else{
            serviceObject=goodsManagementService.add( $scope.entity  );//增加
        }
        serviceObject.success(
            function(response){
                if(200==response.code){
                    alert(response.message);
                    $scope.entity={};
                    editor.html("");//清空富文本编辑器
                    location.href="goods.html";
                }else{
                    if (response.object==null){
                        alert(response.message);
                    }else{
                        alert(response.object);
                    }
                }
            }
        );
    }

    //增加商品
    $scope.add=function(){

        goodsManagementService.add( $scope.entity  ).success(
            function(response){
                if(response.success){

                }else{
                    alert(response.message);
                }
            }
        );
    }
    $scope.marketableStatus=["请通过审核","上架中","下架中"];
    //上架商品
    $scope.putAway=function () {
        goodsManagementService.putAway($scope.selectedIds).success(
            function (response) {
                if (200==response.code){
                    $scope.reloadList();//刷新列表
                    $scope.selectedIds=[];
                }else{
                    if (response.object==null){
                        alert(response.message);
                    }else{
                        alert(response.object);
                    }
                }
            }
        );
    }
    //下架商品
    $scope.soldOut=function () {
        goodsManagementService.soldOut( $scope.selectedIds ).success(
            function (response) {
                if (200==response.code){
                    $scope.reloadList();//刷新列表
                    $scope.selectedIds=[];
                }else{
                    if (response.object==null){
                        alert(response.message);
                    }else{
                        alert(response.object);
                    }
                }
            }
        );
    }
    //批量删除
    $scope.delete=function(){
        var confirm1=confirm("你确认要下架并删除吗？");
        if (confirm1){
            //获取选中的复选框
            goodsManagementService.delete( $scope.selectedIds ).success(
                function(response){
                    if(200==response.code){
                        $scope.reloadList();//刷新列表
                        $scope.selectedIds=[];
                    }
                }
            );
        }
    }
    //查询一级分类
    $scope.selectItemCat1List=function () {
        goodsCategoryService.findByParentId(0).success(
            function (response) {
                $scope.itemCat1List=response;
            }
        );
    }
    //查询二级分类
    $scope.$watch("entity.dpGoods.category1Id",function (newValue,oldValue) {
        goodsCategoryService.findByParentId(newValue).success(
            function (response) {
                $scope.itemCat2List=response;
            }
        );
    });
    //查询三级分类
    $scope.$watch("entity.dpGoods.category2Id",function (newValue,oldValue) {
        goodsCategoryService.findByParentId(newValue).success(
            function (response) {
                $scope.itemCat3List=response;
            }
        );
    });
    //查询模板
    $scope.$watch("entity.dpGoods.category3Id",function (newValue,oldValue) {
        goodsCategoryService.findOne(newValue).success(
            function (response) {
                $scope.entity.dpGoods.typeTemplateId=response.typeId;
            }
        );
    });
    //模板变化后
    $scope.$watch("entity.dpGoods.typeTemplateId",function (newValue,oldValue) {
        //查询扩展属性和品牌列表
        goodsTemplateService.findOne(newValue).success(
            function (response) {
                //读取品牌列表
                $scope.brandList=JSON.parse(response.brandIds);
                //判断如果 id 为空就执行，避免和显示商品信息时的冲突
                if ($location.search()['id']==null){

                    $scope.entity.dpGoodsDesc.customAttributeItems=JSON.parse(response.customAttributeItems);
                }

            });
        //查询规格名字及选项
        goodsTemplateService.findSpecIdAndOption(newValue).success(
            function (response) {
                $scope.specIdAndOptionList=response;
            }
        );
    });
    //文件上传
    $scope.uploadFile=function () {
        uploadFileService.uploadFile().success(
            function (response) {
                if (200==response.code){
                    $scope.image_entity.url=response.object;
                }else{
                    alert(response.message)
                }
            }
        );
    }
    $scope.entity={dpGoods:{},dpGoodsDesc:{itemImages:[],specificationItems:[]}};
    //添加到图片列表
    $scope.addPictureList=function () {
        $scope.entity.dpGoodsDesc.itemImages.push($scope.image_entity);
    }
    //从图片列表中移除图片
    $scope.removeImage=function (index) {
        $scope.entity.dpGoodsDesc.itemImages.splice(index,1);
    }

    //更新规格选项属性列表
    $scope.updateSpecifitionAttribute=function ($event,name,value) {
        //判断集合中是否有attributeName 的 key
        var  object=$scope.isAttributeInList($scope.entity.dpGoodsDesc.specificationItems,"attributeName",name);
        //若存在，则把值添加进去
        if (object !=null ){
            //如果选中，则添加
            if ($event.target.checked){
                object.attributeValue.push(value);
            }else{//取消勾选，则删除
                //根据 object的索引位置，删除整个 object
                object.attributeValue.splice(object.attributeValue.indexOf(value),1);
                if(object.attributeValue.length==0){
                    $scope.entity.dpGoodsDesc.specificationItems.splice(
                        $scope.entity.dpGoodsDesc.specificationItems.indexOf(object),1);
                }
            }
        }else{
            //不存在，把 key 和 key 对应的值添加进去
            $scope.entity.dpGoodsDesc.specificationItems.push({"attributeName":name,"attributeValue":[value]});
        }
    }
    //创建 sku 列表
    $scope.createItemList=function () {
        //定义 sku 的格式
        $scope.entity.dpItemList=[{spec:{},price:'',num:'',status:'0',isDefault:'0'}];
        //得到商品详情表中规格选项
        var items=$scope.entity.dpGoodsDesc.specificationItems;
        for(var i=0;i<items.length;i++){
            //调用添加列的方法，导出所有可能的规格配置
            $scope.entity.dpItemList =$scope.addColumn( $scope.entity.dpItemList,
                items[i].attributeName,items[i].attributeValue);

        }
    }
    //添加规格名列
    $scope.addColumn=function (list,ColumnName,ColumnValue) {
        var newList=[];
        for (var i=0;i<list.length;i++){
            var oldRow=list[i];
            for( var j=0;j<ColumnValue.length;j++){
                var newRow=JSON.parse(JSON.stringify(oldRow));
                newRow.spec[ColumnName]= ColumnValue[j];
                newList.push(newRow);
            }
        }
        return newList;
    }
    //检查规格是否选中
    $scope.checkAttribute=function (AttributeName,AttributeValue) {
        var item=$scope.entity.dpGoodsDesc.specificationItems;
        //判断列表中是否包含 key=attributeName，value=attributeName的元素
        var object=$scope.isAttributeInList(item,"attributeName",AttributeName);
        if(object != null ){//包含此元素
            //判断attributeValue是否含有AttributeValue
            if (object.attributeValue.indexOf(AttributeValue)>=0){
                return true;
            }else{
                return false;
            }
        }else{//不包含返回false
            return false;
        }
    }
    //设置对应关系，0 为未申请，1 为申请中
    $scope.status=["未申请","申请中","审核通过","已驳回"];
    $scope.goodsCatList=[];
    //找到商品分类列表
    $scope.findGoodsCatList=function () {
        goodsCategoryService.findAll().success(
            function (response) {
                for (var i=0;i<response.length;i++){
                    $scope.goodsCatList[response[i].id]=response[i].name;
                }
            }
        )
    }

});
